import json

import requests
from django.core.cache import cache

from employee.models import *
from scanQrCode.models import ScanEmployee
from utils.token import Token


def _request(method, url, data, headers=None):
    if method == 'post':
        if headers is None:
            res = requests.post(url=url, data=data)
        else:
            res = requests.post(url=url, data=data, headers=headers)
    if method == 'get':
        if headers is None:
            res = requests.get(url=url, params=data)
        else:
            res = requests.get(url=url, params=data, headers=headers)
    result = json.loads(res.text)
    return result


def _lb(lb):
    lb_dict = {
        '0/107201/107202': 'DL',
        '0/107201/107203': 'IDL',
        '0/107201/107204': 'SAL',
    }
    return lb_dict.get(lb)


def _gender(gender):
    gender_dict = {
        '0/599/604': 1,
        '0/599/605': 2,
    }
    return gender_dict.get(gender)


def _pay_type(pay_type):
    pay_type_dict = {
        '0/102805/102806': 1,
        '0/102805/102807': 2,
    }
    return pay_type_dict.get(pay_type)


class DayeeInterface:
    def __init__(self):
        self.corpCode = 'RUNERGY'
        self.userName = 'runergy'
        self.password = '976DAE1C4F352A1606B95D7D06AD472B'
        self.getTokenUrl = 'https://api.wintalent.cn/wt/api/2.0/getToken'
        self.getOfficeUrl = 'https://api.wintalent.cn/wt/api/2.0/auth/resume/getOffer'
        self.getInterviewUrl = 'https://api.wintalent.cn/wt/api/2.0/auth/resume/getInterview'
        self.callbackForRead = 'https://api.wintalent.cn/wt/api/2.0/auth/resume/callbackForRead'

    def get_token(self):
        bodyStr = {
            "corpCode": self.corpCode,
            "userName": self.userName,
            "password": self.password
        }
        values_json = json.dumps(bodyStr)
        return_data = _request('post', self.getTokenUrl, values_json)
        cache.set('dayeeToken', return_data['data']['token'], 29 * 60)

    def get_office(self):
        """
        获取大易office，如果没有Nbxxcj或Nbxxcj里的参数为空，则返回已读
        :return:
        """
        token = cache.get('dayeeToken')
        if token:
            bodyStr = {
                "cType": "1,3",
                "offerStatus": "6",
                "rowSize": 100
            }
            headers = {
                'Authorization': "Bearer " + token
            }
            bodyStr = json.dumps(bodyStr)
            office_list = _request('post', self.getOfficeUrl, bodyStr, headers)
            if office_list['data'].get('resume'):
                applyIds = ''
                for resume in office_list['data']['resume']:
                    try:
                        Nbxxcj = resume['offerInfo']['Nbxxcj']
                        if Nbxxcj and Nbxxcj['Offerzd'] != '':
                            emp_predict_entry_date = resume['offerInfo']['录用通知书信息字段']['ruzhishijian'].replace('年', '-')
                            emp_predict_entry_date = emp_predict_entry_date.replace('月', '-')
                            emp_predict_entry_date = emp_predict_entry_date.replace('日', '')
                            emp_predict_entry_date = emp_predict_entry_date.replace('/', '-')
                            ScanEmployee.objects.update_or_create(
                                defaults={
                                    'emp_name': resume['resumeContent']['personalInformation']['name'],
                                    'emp_dept': EmpDepartment.objects.get(department_code=Nbxxcj['Bmbm']),
                                    'emp_post_id': EmpPosition.objects.filter(post_name=resume['offerInfo']['录用通知书信息字段']['yingpinzhiwei']).values('id')[0]['id'] if EmpPosition.objects.filter(
                                        post_name=resume['offerInfo']['录用通知书信息字段']['yingpinzhiwei']).exists() else 999,
                                    'emp_job_duty_id': EmpJobDuty.objects.filter(job_duty_name=Nbxxcj['Offerzw']).values('id')[0]['id'] if EmpJobDuty.objects.filter(
                                        job_duty_name=Nbxxcj['Offerzw']).exists() else 999,
                                    'emp_job_class_id': EmpJobClass.objects.filter(job_class_name=Nbxxcj['Offerzd']).values('id')[0]['id'] if EmpJobClass.objects.filter(
                                        job_class_name=Nbxxcj['Offerzd']).exists() else 999,
                                    'emp_job_grade_id': EmpJobGrade.objects.filter(job_grade_name=Nbxxcj['Offerzj']).values('id')[0]['id'] if EmpJobGrade.objects.filter(
                                        job_grade_name=Nbxxcj['Offerzj']).exists() else 999,
                                    'emp_job_rank_id': EmpJobRank.objects.filter(job_rank_name=Nbxxcj['Htgs']).values('id')[0]['id'] if EmpJobRank.objects.filter(
                                        job_rank_name=Nbxxcj['Htgs']).exists() else 999,
                                    'emp_dl_idl': _lb(Nbxxcj['lb']),
                                    'emp_predict_entry_date': emp_predict_entry_date,
                                    'emp_pay_type_id': _pay_type(resume['offerInfo']['录用通知书信息字段']['jixinfangshi']),
                                    'emp_id_card': resume['resumeContent']['personalInformation']['iDNUM'],
                                    'emp_gender': _gender(resume['resumeContent']['personalInformation']['gender']),
                                },
                                emp_predict_entry_date=emp_predict_entry_date,
                                emp_name=resume['resumeContent']['personalInformation']['name'],
                                emp_id_card=resume['resumeContent']['personalInformation']['iDNUM'],
                            )
                            applyIds = applyIds + str(resume['applyId']) + ','
                    except Exception as e:
                        print(e)
                        # applyIds = applyIds + str(resume['applyId']) + ','
                callbacl_data = {
                    "cType": "1",
                    "applyIds": applyIds[:-1]
                }
                callback_res = _request('post', self.callbackForRead, json.dumps(callbacl_data), headers)

        else:
            self.get_token()
            self.get_office()

    def get_interview(self, current_page):
        """
        获取简历数据，蓝领和内荐使用
        :return:
        """
        token = cache.get('dayeeToken')
        if token:
            bodyStr = {
                "cType": "1,18",
                "applyStatus": "9",
                "postRecruitType": "8,13",
                "rowSize": 100,
                "evaluatestatus": 2,
                "currentPage": current_page
            }
            headers = {
                'Authorization': "Bearer " + token
            }
            bodyStr = json.dumps(bodyStr)
            interview_list = _request('post', self.getInterviewUrl, bodyStr, headers)
            if interview_list['data'].get('resume'):
                applyIds = ''
                if interview_list['data'].get('resume') and len(interview_list['data']['resume']) > 0:
                    try:
                        for resume in interview_list['data']['resume']:
                            # 取标签数据判断是否位蓝领招聘，如果是则取数据并返回，如果不是则不处理
                            if 100502 in [label_id['labelId'] for label_id in resume['basicInfo']['labelInfo']]:
                                Nbxxcj = resume['resumeContent']['Llnbxxcj']
                                print(Nbxxcj)
                                print(resume['resumeContent']['personalInformation'])
                                emp_predict_entry_date = Nbxxcj['Jlrzsj']
                                emp_predict_entry_date = emp_predict_entry_date.replace('年', '-')
                                emp_predict_entry_date = emp_predict_entry_date.replace('月', '-')
                                emp_predict_entry_date = emp_predict_entry_date.replace('日', '')
                                emp_predict_entry_date = emp_predict_entry_date.replace('/', '-')
                                ScanEmployee.objects.update_or_create(
                                    defaults={
                                        'emp_name': resume['resumeContent']['personalInformation']['name'],
                                        'emp_dept': EmpDepartment.objects.get(department_code=Nbxxcj['Jlbmbm']),
                                        'emp_post_id': EmpPosition.objects.filter(post_name=Nbxxcj['Jtrzgw']).values('id')[0]['id'] if EmpPosition.objects.filter(post_name=Nbxxcj['Jtrzgw']).exists() else 999,
                                        'emp_job_rank_id': EmpJobRank.objects.filter(job_rank_name=Nbxxcj['Jlhtgs']).values('id')[0]['id'] if EmpJobRank.objects.filter(job_rank_name=Nbxxcj['Jlhtgs']).exists() else 999,
                                        'emp_dl_idl': _lb(Nbxxcj['Jllb']),
                                        'emp_predict_entry_date': emp_predict_entry_date,
                                        'emp_pay_type_id': _pay_type(Nbxxcj['Jljxfs']),
                                        'emp_id_card': resume['resumeContent']['personalInformation']['iDNUM'],
                                        'emp_gender': _gender(resume['resumeContent']['personalInformation']['gender']),
                                    },
                                    emp_predict_entry_date=emp_predict_entry_date,
                                    emp_name=resume['resumeContent']['personalInformation']['name'],
                                    emp_id_card=resume['resumeContent']['personalInformation']['iDNUM'],
                                )
                                applyIds = applyIds + str(resume['applyId']) + ','
                        callbacl_data = {
                            "cType": "1",
                            "applyIds": applyIds[:-1]
                        }
                        callback_res = _request('post', self.callbackForRead, json.dumps(callbacl_data), headers)
                    except Exception as e:
                        print(e)
            if interview_list['data']['pageCount'] > current_page:
                self.get_interview(current_page + 1)
        else:
            self.get_token()
            self.get_interview(current_page)

def log():
    print(1)